package com.arun.datasource;

import java.beans.PropertyVetoException;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
//@SpringBootApplication
@MapperScan(basePackages={"com.arun.mappers","com.arun.dao.ssm"},sqlSessionFactoryRef = "dbssmSqlSessionFactory") // Mybatis mapper
public class DataSourceConfiguration {
  @Value("${spring.datasource.driver-class-name}")
  private String driver;
  @Value("${spring.datasource.url}")
  private String url;
  @Value("${spring.datasource.username}")
  private String username;
  @Value("${spring.datasource.password}")
  private String password;
  
  @Primary
  @Bean(name = "dbtestDataSource")
  public DataSource createDataSource() throws PropertyVetoException, SQLException {
      ComboPooledDataSource dataSource = new ComboPooledDataSource();
      dataSource.setDriverClass(driver);
      dataSource.setJdbcUrl(url);
      dataSource.setUser(username);
      dataSource.setPassword(password);
      dataSource.setAutoCommitOnClose(false);
      dataSource.setInitialPoolSize(10);
      dataSource.setMinPoolSize(10);
      dataSource.setMaxPoolSize(100);
      dataSource.getConnection();	// spring boot启动时初始化c3p0连接池
      System.out.print("ssm========================================="+dataSource+"===========================================");
      
      return dataSource;
  }
  
  @Primary
  @Bean(name = "dbssmSqlSessionFactory")
  public SqlSessionFactory sqlSessionFactory(@Qualifier("dbtestDataSource") DataSource dataSource) throws Exception {
      SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
      sessionFactoryBean.setDataSource(dataSource);
      sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/arun/mappers/*.xml"));
      System.out.println("==================ssm======================");
      return sessionFactoryBean.getObject();
  }
	
}